/*
 * SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */

 /****************************************************************************
  *
  * This demo showcases creating a GATT database using a predefined attribute table.
  * It acts as a GATT server and can send adv data, be connected by client.
  * Run the gatt_client demo, the client demo will automatically connect to the gatt_server_service_table demo.
  * Client demo will enable GATT server's notify after connection. The two devices will then exchange
  * data.
  *
  ****************************************************************************/

#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"

#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_main.h"
#include "gatts_table_creat_demo.h"
#include "esp_gatt_common_api.h"

#include "./mycode/led/led.h"
#include "./mycode/UART/myuart.h"

#define GATTS_TABLE_TAG "ESP32C6"

#define PROFILE_NUM 1
#define PROFILE_APP_IDX 0
#define ESP_APP_ID 0x55
#define SAMPLE_DEVICE_NAME "ESP32C6_GATTS_HC"
#define SVC_INST_ID 0

  /* The max length of characteristic value. When the GATT client performs a write or prepare write operation,
   *  the data length must be less than GATTS_DEMO_CHAR_VAL_LEN_MAX.
   */
#define GATTS_DEMO_CHAR_VAL_LEN_MAX 512
#define PREPARE_BUF_MAX_SIZE 2048
#define CHAR_DECLARATION_SIZE (sizeof(uint8_t))

#define ADV_CONFIG_FLAG (1 << 0)
#define SCAN_RSP_CONFIG_FLAG (1 << 1)

static uint8_t adv_config_done = 0;

uint16_t heart_rate_handle_table[HRS_IDX_NB];

typedef struct
{
    uint8_t* prepare_buf;
    int prepare_len;
} prepare_type_env_t;

//#define CONFIG_SET_RAW_ADV_DATA
#ifdef CONFIG_SET_RAW_ADV_DATA

// 发送的广播包，现在名字在这个里面改
// 类型详见 Assigned_Numbers 中的 Common Data Types 小节
static uint8_t raw_adv_data[] = {
    //  长度  类型  数据
    /* flags */
    0x02, 0x01, 0x06,
    /* tx power*/
    0x02, 0x0a, 0xeb,
    /* service uuid */
    0x03, 0x03, 0xFF, 0x00,
    /* device name */
    0x0e, 0x09, 'E', 'S', 'P', '3', '2', '-', 'G', 'A', 'T', 'T', '-', 'H', 'C' };
//应答数据包
static uint8_t raw_scan_rsp_data[] = {
    //  长度  类型  数据
    /* flags */
    0x02, 0x01, 0x06,
    /* tx power */
    0x02, 0x0a, 0xeb,
    /* service uuid */
    0x03, 0x03, 0xFF, 0x00 };

#else
static uint8_t service_uuid[16] = {
    /* LSB <--------------------------------------------------------------------------------> MSB */
    // first uuid, 16bit, [12],[13] is the value
    0xfb,
    0x34,
    0x9b,
    0x5f,
    0x80,
    0x00,
    0x00,
    0x80,
    0x00,
    0x10,
    0x00,
    0x00,
    0xFF,
    0x00,
    0x00,
    0x00,
};

/* The length of adv data must be less than 31 bytes */
static esp_ble_adv_data_t adv_data = {
    .set_scan_rsp = false,
    .include_name = true,
    .include_txpower = true,
    .min_interval = 0x0006, // slave connection min interval, Time = min_interval * 1.25 msec
    .max_interval = 0x0010, // slave connection max interval, Time = max_interval * 1.25 msec
    .appearance = 0x00,
    .manufacturer_len = 0,       // TEST_MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = NULL, // test_manufacturer,
    .service_data_len = 0,
    .p_service_data = NULL,
    .service_uuid_len = sizeof(service_uuid),
    .p_service_uuid = service_uuid,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};

// scan response data
static esp_ble_adv_data_t scan_rsp_data = {
    .set_scan_rsp = true,
    .include_name = true,
    .include_txpower = true,
    .min_interval = 0x0006,
    .max_interval = 0x0010,
    .appearance = 0x00,
    .manufacturer_len = 0,       // TEST_MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = NULL, //&test_manufacturer[0],
    .service_data_len = 0,
    .p_service_data = NULL,
    .service_uuid_len = sizeof(service_uuid),
    .p_service_uuid = service_uuid,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};
#endif /* CONFIG_SET_RAW_ADV_DATA */

static esp_ble_adv_params_t adv_params = {
    .adv_int_min = 0x20,
    .adv_int_max = 0x40,
    .adv_type = ADV_TYPE_IND,
    .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
    .channel_map = ADV_CHNL_ALL,
    .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

struct gatts_profile_inst
{
    esp_gatts_cb_t gatts_cb;
    uint16_t gatts_if;
    uint16_t app_id;
    uint16_t conn_id;
    uint16_t service_handle;
    esp_gatt_srvc_id_t service_id;
    uint16_t char_handle;
    esp_bt_uuid_t char_uuid;
    esp_gatt_perm_t perm;
    esp_gatt_char_prop_t property;
    uint16_t descr_handle;
    esp_bt_uuid_t descr_uuid;
};

static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
    esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param);

/* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
static struct gatts_profile_inst heart_rate_profile_tab[PROFILE_NUM] = {
    [PROFILE_APP_IDX] = {
        .gatts_cb = gatts_profile_event_handler,
        .gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
};

/* Service */
// 设置服务的值
static const uint16_t GATTS_SERVICE_UUID = 0x00FF;
static const uint16_t GATTS_CHAR_UUID_Car_control = 0xFF01;
static const uint16_t GATTS_CHAR_UUID_Euler_angle = 0xFF02;
static const uint16_t GATTS_CHAR_UUID_Horizontal_angle = 0xFF03;
static const uint16_t GATTS_CHAR_UUID_Distances = 0xFF04;
static const uint16_t GATTS_CHAR_UUID_Battery = 0xFF05;
static const uint16_t GATTS_CHAR_UUID_Bmp180 = 0xFF06;


static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE;
static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE;
static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ;
static const uint8_t char_prop_write = ESP_GATT_CHAR_PROP_BIT_WRITE;

uint8_t Euler_angle_value[12] = { 0 };
uint8_t Horizontal_angle[12] = { 0 };
uint8_t Distances[16] = { 0 };
uint8_t Battery[4] = { 0 };
uint8_t bmp180[12] = { 0 };
uint8_t ready_receive = 0;


/* Full Database Description - Used to add attributes into the database */
static const esp_gatts_attr_db_t gatt_db[HRS_IDX_NB] =
{
    // Service Declaration
    [IDX_SVC] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&primary_service_uuid,
         ESP_GATT_PERM_READ, sizeof(uint16_t), sizeof(GATTS_SERVICE_UUID), (uint8_t*)&GATTS_SERVICE_UUID}},

    /* Characteristic Declaration */
    [IDX_CHAR_Car_control] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
         ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
          (uint8_t*)&char_prop_write}}, // 可写

    /* Characteristic Value */
    [IDX_CHAR_VAL_Car_control] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Car_control,
         ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
          sizeof(Euler_angle_value), (uint8_t*)Euler_angle_value}},

    /* Characteristic Declaration */
    [IDX_CHAR_Euler_angle] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
         ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
          (uint8_t*)&char_prop_read}}, // 可读

    /* Characteristic Value */
    [IDX_CHAR_VAL_Euler_angle] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Euler_angle,
         ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
          sizeof(Euler_angle_value), (uint8_t*)Euler_angle_value}},

    /* Characteristic Declaration */
    [IDX_CHAR_Horizontal_angle] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
     ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
      (uint8_t*)&char_prop_read}}, // 可读

    /* Characteristic Value */
    [IDX_CHAR_VAL_Horizontal_angle] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Horizontal_angle,
         ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
          sizeof(Horizontal_angle), (uint8_t*)Horizontal_angle}},

    /* Characteristic Declaration */
    [IDX_CHAR_Distances] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
     ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
      (uint8_t*)&char_prop_read}}, // 可读

    /* Characteristic Value */
    [IDX_CHAR_VAL_Distances] =
        {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Distances,
         ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
          sizeof(Distances), (uint8_t*)Distances}},

    /* Characteristic Declaration */
    [IDX_CHAR_Battery] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
    ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
    (uint8_t*)&char_prop_read}}, // 可读

    /* Characteristic Value */
    [IDX_CHAR_VAL_Battery] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Battery,
    ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
    sizeof(Battery), (uint8_t*)Battery}},

    /* Characteristic Declaration */
    [IDX_CHAR_bmp180] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&character_declaration_uuid,
    ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE,
    (uint8_t*)&char_prop_read}}, // 可读

    /* Characteristic Value */
    [IDX_CHAR_VAL_bmp180] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t*)&GATTS_CHAR_UUID_Bmp180,
    ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, GATTS_DEMO_CHAR_VAL_LEN_MAX,
    sizeof(bmp180), (uint8_t*)bmp180}},
};

static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param)
{
    switch (event)
    {
#ifdef CONFIG_SET_RAW_ADV_DATA
    case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT://广播数据设置完成
        adv_config_done &= (~ADV_CONFIG_FLAG);
        if (adv_config_done == 0)
        {
            esp_ble_gap_start_advertising(&adv_params);//开启广播
        }
        break;
    case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT://应答数据设置完成
        adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
        if (adv_config_done == 0)
        {
            esp_ble_gap_start_advertising(&adv_params);//开启应答
        }
        break;
#else
    case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
        adv_config_done &= (~ADV_CONFIG_FLAG);
        if (adv_config_done == 0)
        {
            esp_ble_gap_start_advertising(&adv_params);
        }
        break;
    case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT:
        adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
        if (adv_config_done == 0)
        {
            esp_ble_gap_start_advertising(&adv_params);
        }
        break;
#endif
    case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
        /* advertising start complete event to indicate advertising start successfully or failed */
        if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "广播 启动 失败");
        }
        else
        {
            ESP_LOGI(GATTS_TABLE_TAG, "广播 启动 成功");
        }
        break;
    case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
        if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "广播 停止 失败");
        }
        else
        {
            ESP_LOGI(GATTS_TABLE_TAG, "广播 停止 成功");
        }
        break;
    case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "update connection params status = %d, min_int = %d, max_int = %d,conn_int = %d,latency = %d, timeout = %d",
            param->update_conn_params.status,
            param->update_conn_params.min_int,
            param->update_conn_params.max_int,
            param->update_conn_params.conn_int,
            param->update_conn_params.latency,
            param->update_conn_params.timeout);
        break;
    default:
        break;
    }
}

static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param)
{
    switch (event)
    {
    case ESP_GATTS_REG_EVT:
    {
        //设置设备名字
        esp_err_t set_dev_name_ret = esp_ble_gap_set_device_name(SAMPLE_DEVICE_NAME);
        if (set_dev_name_ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "set device name failed, error code = %x", set_dev_name_ret);
        }
#ifdef CONFIG_SET_RAW_ADV_DATA
        //设置发送的广播数据
        esp_err_t raw_adv_ret = esp_ble_gap_config_adv_data_raw(raw_adv_data, sizeof(raw_adv_data));
        if (raw_adv_ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "config raw adv data failed, error code = %x ", raw_adv_ret);
        }
        adv_config_done |= ADV_CONFIG_FLAG;
        //设置应答的数据
        esp_err_t raw_scan_ret = esp_ble_gap_config_scan_rsp_data_raw(raw_scan_rsp_data, sizeof(raw_scan_rsp_data));
        if (raw_scan_ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "config raw scan rsp data failed, error code = %x", raw_scan_ret);
        }
        adv_config_done |= SCAN_RSP_CONFIG_FLAG;
#else
        // config adv data
        esp_err_t ret = esp_ble_gap_config_adv_data(&adv_data);
        if (ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret);
        }
        adv_config_done |= ADV_CONFIG_FLAG;
        // config scan response data
        ret = esp_ble_gap_config_adv_data(&scan_rsp_data);
        if (ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "config scan response data failed, error code = %x", ret);
        }
        adv_config_done |= SCAN_RSP_CONFIG_FLAG;
#endif
        esp_err_t create_attr_ret = esp_ble_gatts_create_attr_tab(gatt_db, gatts_if, HRS_IDX_NB, SVC_INST_ID);
        if (create_attr_ret)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "create attr table failed, error code = %x", create_attr_ret);
        }
    }
    break;
    case ESP_GATTS_READ_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_READ_EVT, handle = %d", param->read.handle);
        uint8_t control_code[4] = { 0 };
        if (ready_receive == 0)
        {
            control_code[0] = 0x01;
            control_code[1] = 0x00;
            control_code[2] = 0x00;
            control_code[3] = 0x01;
            uart_sendData("要求传输欧拉角数据", (uint8_t*)&control_code);
            vTaskDelay(200 / portTICK_PERIOD_MS);
            control_code[0] = 0x01;
            control_code[1] = 0x00;
            control_code[2] = 0x00;
            control_code[3] = 0x02;
            uart_sendData("要求传输水平倾斜角数据", (uint8_t*)&control_code);
            vTaskDelay(200 / portTICK_PERIOD_MS);
            control_code[0] = 0x01;
            control_code[1] = 0x00;
            control_code[2] = 0x00;
            control_code[3] = 0x03;
            uart_sendData("要求传输四周距离", (uint8_t*)&control_code);
            vTaskDelay(200 / portTICK_PERIOD_MS);
            control_code[0] = 0x01;
            control_code[1] = 0x00;
            control_code[2] = 0x00;
            control_code[3] = 0x04;
            uart_sendData("要求传输电池电量", (uint8_t*)&control_code);
            vTaskDelay(200 / portTICK_PERIOD_MS);
            control_code[0] = 0x01;
            control_code[1] = 0x00;
            control_code[2] = 0x00;
            control_code[3] = 0x05;
            uart_sendData("要求传输BMP180数据", (uint8_t*)&control_code);
            vTaskDelay(200 / portTICK_PERIOD_MS);
            ready_receive = 1;
        }
        bzero(control_code, sizeof(control_code));

        break;
    case ESP_GATTS_WRITE_EVT:
        if (!param->write.is_prep)//准备写
        {
            //ESP_LOGI(GATTS_TABLE_TAG, "GATT_WRITE_EVT, handle = %d, value len = %d", param->write.handle, param->write.len);
            //二操作码控制
            if (heart_rate_handle_table[IDX_CHAR_VAL_Car_control] == param->write.handle)
            {
                uint8_t control_code[4] = { 0 };
                control_code[0] = param->write.value[0];
                control_code[1] = param->write.value[1];
                control_code[2] = param->write.value[2];
                //ESP_LOGE(GATTS_TABLE_TAG, "GATT_WRITE_EVT value : %0x %0x", control_code[0],control_code[1]);
                //ESP_LOGI(GATTS_TABLE_TAG, "GATT_WRITE_EVT control_code : %0x %0x %0d", control_code[0],
                //control_code[1], control_code[2]);
                //0x00XX用于控制车辆电机
                if (control_code[0] == 0x00)
                {
                    if (control_code[1] == 0x01)
                    {//设置速度
                        ESP_LOGW(GATTS_TABLE_TAG, "The car speed  %d", control_code[2]);
                        uart_sendData("speed", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x02)
                    {//前进 foward
                        ESP_LOGW(GATTS_TABLE_TAG, "The car foward!");
                        uart_sendData("foward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x03)
                    {//后退 backward
                        ESP_LOGW(GATTS_TABLE_TAG, "The car backward!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x04)
                    {//左平移 Left shift
                        ESP_LOGW(GATTS_TABLE_TAG, "The car Left shift!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x05)
                    {//右平移 right shift
                        ESP_LOGW(GATTS_TABLE_TAG, "The car right shift!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x06)
                    {//左转 Left
                        ESP_LOGW(GATTS_TABLE_TAG, "The car Left!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x07)
                    {//右转 right
                        ESP_LOGW(GATTS_TABLE_TAG, "The car right!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                    else if (control_code[1] == 0x08)
                    {//停止 stop
                        control_code[3] = 0xff;
                        ESP_LOGW(GATTS_TABLE_TAG, "The car stop!");
                        uart_sendData("backward", (uint8_t*)&control_code);
                    }
                }
                //0x01XX用于控制车辆设备
                else if (control_code[0] == 0x01)
                {
                    ESP_LOGI(GATTS_TABLE_TAG, "The LED is ON!");
                    LED_Flip();
                }
                else
                {
                    esp_log_buffer_hex(GATTS_TABLE_TAG, param->write.value, param->write.len);
                }
            }
            /* send response when param->write.need_rsp is true*/
            if (param->write.need_rsp)
            {
                esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, NULL);
            }
        }
        break;
    case ESP_GATTS_EXEC_WRITE_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_EXEC_WRITE_EVT");
        break;
    case ESP_GATTS_MTU_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_MTU_EVT, MTU %d", param->mtu.mtu);
        break;
    case ESP_GATTS_CONF_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_CONF_EVT, status = %d, attr_handle %d", param->conf.status, param->conf.handle);
        break;
    case ESP_GATTS_START_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "SERVICE_START_EVT, status %d, service_handle %d", param->start.status, param->start.service_handle);
        break;
    case ESP_GATTS_CONNECT_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_CONNECT_EVT, conn_id = %d", param->connect.conn_id);
        esp_log_buffer_hex(GATTS_TABLE_TAG, param->connect.remote_bda, 6);
        esp_ble_conn_update_params_t conn_params = { 0 };
        memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
        /* For the iOS system, please refer to Apple official documents about the BLE connection parameters restrictions. */
        conn_params.latency = 0;
        conn_params.max_int = 0x20; // max_int = 0x20*1.25ms = 40ms
        conn_params.min_int = 0x10; // min_int = 0x10*1.25ms = 20ms
        conn_params.timeout = 400;  // timeout = 400*10ms = 4000ms
        // start sent the update connection parameters to the peer device.
        esp_ble_gap_update_conn_params(&conn_params);
        break;
    case ESP_GATTS_DISCONNECT_EVT:
        ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_DISCONNECT_EVT, reason = 0x%x", param->disconnect.reason);
        esp_ble_gap_start_advertising(&adv_params);
        break;
    case ESP_GATTS_CREAT_ATTR_TAB_EVT:
    {
        if (param->add_attr_tab.status != ESP_GATT_OK)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "create attribute table failed, error code=0x%x", param->add_attr_tab.status);
        }
        else if (param->add_attr_tab.num_handle != HRS_IDX_NB)
        {
            ESP_LOGE(GATTS_TABLE_TAG, "create attribute table abnormally, num_handle (%d) \
                            doesn't equal to HRS_IDX_NB(%d)", param->add_attr_tab.num_handle, HRS_IDX_NB);
        }
        else
        {
            ESP_LOGI(GATTS_TABLE_TAG, "create attribute table successfully, the number handle = %d\n", param->add_attr_tab.num_handle);
            memcpy(heart_rate_handle_table, param->add_attr_tab.handles, sizeof(heart_rate_handle_table));
            esp_ble_gatts_start_service(heart_rate_handle_table[IDX_SVC]);
        }
        break;
    }
    case ESP_GATTS_STOP_EVT:
    case ESP_GATTS_OPEN_EVT:
    case ESP_GATTS_CANCEL_OPEN_EVT:
    case ESP_GATTS_CLOSE_EVT:
    case ESP_GATTS_LISTEN_EVT:
    case ESP_GATTS_CONGEST_EVT:
    case ESP_GATTS_UNREG_EVT:
    case ESP_GATTS_DELETE_EVT:
    default:
        break;
    }
}

static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param)
{

    /* If event is register event, store the gatts_if for each profile */
    if (event == ESP_GATTS_REG_EVT)
    {
        if (param->reg.status == ESP_GATT_OK)
        {
            heart_rate_profile_tab[PROFILE_APP_IDX].gatts_if = gatts_if;
        }
        else
        {
            ESP_LOGE(GATTS_TABLE_TAG, "reg app failed, app_id %04x, status %d",
                param->reg.app_id,
                param->reg.status);
            return;
        }
    }
    do
    {
        int idx;
        for (idx = 0; idx < PROFILE_NUM; idx++)
        {
            /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
            if (gatts_if == ESP_GATT_IF_NONE || gatts_if == heart_rate_profile_tab[idx].gatts_if)
            {
                if (heart_rate_profile_tab[idx].gatts_cb)
                {
                    heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param);
                }
            }
        }
    } while (0);
}

void rx_task(void* arg)
{
    static const char* RX_TASK_TAG = "RX_TASK";
    esp_log_level_set(RX_TASK_TAG, ESP_LOG_INFO);
    uint8_t* data = (uint8_t*)malloc(uart_buffer_size + 1);
    while (1)
    {
        const int rxBytes = uart_read_bytes(UART_NUM_1, data, uart_buffer_size, 1000 / portTICK_PERIOD_MS);
        if (rxBytes > 0)
        {
            data[rxBytes] = 0;
            ESP_LOGI(RX_TASK_TAG, "Read %d bytes", rxBytes);
            ESP_LOG_BUFFER_HEXDUMP(RX_TASK_TAG, data, rxBytes, ESP_LOG_INFO);
            int i;
            float da = 0, db = 0, dc = 0, dd = 0;
            float* p;
            if (ready_receive == 1)
            {//接收欧拉角数据
                for (i = 0; i < 12; i++)
                {
                    Euler_angle_value[i] = *((uint8_t*)data + i + 1);
                    printf("%x ", Euler_angle_value[i]);
                }
                p = &da;
                for (i = 0;i < sizeof(da);i++)
                {
                    *((char*)p + i) = Euler_angle_value[i];
                }
                p = &db;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Euler_angle_value[i + 4];
                }
                p = &dc;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Euler_angle_value[i + 8];
                }
                printf("\n");
                printf("欧拉角 上下:%f\n", da);
                printf("欧拉角 左右:%f\n", db);
                printf("欧拉角 翻滚:%f\n", dc);
                esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_Euler_angle], sizeof(Euler_angle_value), (uint8_t*)Euler_angle_value);
                //接收水平倾角数据
                for (i = 0; i < 12; i++)
                {
                    Horizontal_angle[i] = *((uint8_t*)data + i + 33);
                    printf("%x ", Horizontal_angle[i]);
                }
                p = &da;
                for (i = 0;i < sizeof(da);i++)
                {
                    *((char*)p + i) = Horizontal_angle[i];
                }
                p = &db;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Horizontal_angle[i + 4];
                }
                p = &dc;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Horizontal_angle[i + 8];
                }
                printf("\n");
                printf("水平倾角 上下:%f\n", da);
                printf("水平倾角 左右:%f\n", db);
                printf("水平倾角 翻滚:%f\n", dc);
                esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_Horizontal_angle], sizeof(Horizontal_angle), (uint8_t*)Horizontal_angle);
                //接收四周Distances数据
                for (i = 0; i < 16; i++)
                {
                    Distances[i] = *((uint8_t*)data + i + 65);
                    printf("%x ", Distances[i]);
                }
                p = &da;
                for (i = 0;i < sizeof(da);i++)
                {
                    *((char*)p + i) = Distances[i];
                }
                p = &db;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Distances[i + 4];
                }
                p = &dc;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Distances[i + 8];
                }
                p = &dd;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = Distances[i + 12];
                }
                printf("\n");
                printf("测距 前:%f cm\n", da);
                printf("测距 后:%f cm\n", db);
                printf("测距 左:%f cm\n", dc);
                printf("测距 右:%f cm\n", dc);
                esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_Distances], sizeof(Distances), (uint8_t*)Distances);
                //接收Battery电量数据
                for (i = 0; i < 4; i++)
                {
                    Battery[i] = *((uint8_t*)data + i + 97);
                    printf("%x ", Battery[i]);
                }
                p = &da;
                for (i = 0;i < sizeof(da);i++)
                {
                    *((char*)p + i) = Battery[i];
                }
                printf("\n");
                printf("电池电量:%f %%\n", da);
                esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_Battery], sizeof(Battery), (uint8_t*)Battery);
                //接收BMP180电数据
                for (i = 0; i < 12; i++)
                {
                    bmp180[i] = *((uint8_t*)data + i + 129);
                    printf("%x ", bmp180[i]);
                }
                p = &da;
                for (i = 0;i < sizeof(da);i++)
                {
                    *((char*)p + i) = bmp180[i];
                }
                p = &db;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = bmp180[i + 4];
                }
                p = &dc;
                for (i = 0;i < sizeof(db);i++)
                {
                    *((char*)p + i) = bmp180[i + 8];
                }
                printf("\n");
                printf("温度:%f ℃\n", da);
                printf("气压:%f kPa\n", db);
                printf("海拔高度:%f m\n", dc);
                esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_bmp180], sizeof(bmp180), (uint8_t*)bmp180);
                ready_receive = 0;
            }
        }
    }
    free(data);
}

void app_main(void)
{
    esp_err_t ret;
    LED_Init();

    /* Initialize NVS.
    nvs初始化
    */
    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    /*
    释放经典蓝牙资源，防止工作在经典蓝牙下
    */
    ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));

    /*
    按默认模式初始化蓝牙控制器，此函数只能被调用一次，且必须在其他蓝牙功能被调用之前调用
    */
    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
    ret = esp_bt_controller_init(&bt_cfg);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
        return;
    }

    /*
    使能蓝牙控制器，工作在 BLE 模式:
    */
    ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
        return;
    }

    /*
    按默认模式初始化蓝牙栈 `bluedroid stack`
    */
    esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
    ret = esp_bluedroid_init_with_cfg(&bluedroid_cfg);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "%s init bluetooth failed: %s", __func__, esp_err_to_name(ret));
        return;
    }

    ret = esp_bluedroid_enable();
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "%s enable bluetooth failed: %s", __func__, esp_err_to_name(ret));
        return;
    }

    ret = esp_ble_gatts_register_callback(gatts_event_handler);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "gatts register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gap_register_callback(gap_event_handler);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "gap register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gatts_app_register(ESP_APP_ID);
    if (ret)
    {
        ESP_LOGE(GATTS_TABLE_TAG, "gatts app register error, error code = %x", ret);
        return;
    }

    esp_ble_gatt_set_local_mtu(512);

    myuart_Init();

    xTaskCreate(rx_task, "uart_rx_task", 1024 * 2, NULL, configMAX_PRIORITIES - 1, NULL);
}